<template>
  <div class="following_change">
    <searchBox>
      <template #yyxbread>
        <div style="display: flex; align-items: center">
          <el-icon>
            <Location />
          </el-icon>
          <span class="f12 ml10 mr10">当前位置：</span>
          <el-breadcrumb separator="/" class="f14">
            <el-breadcrumb-item>预算报价</el-breadcrumb-item>
            <el-breadcrumb-item class="active">预算报价变更</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </template>
    </searchBox>
    <div class="change_content" v-loading="loading">
      <div class="content_box">
        <div class="box_left">
          <div class="left_title mb20">编辑变更材料</div>
          <div class="left_content mb20">
            <div class="content_title">
              {{ detailInfo.budgetType === 1 ? "合计总造价：" : "套餐合计" }}
              <span class="title_num">¥{{ detailInfo.budgetTotlalMoney }}</span>
            </div>
            <div v-if="detailInfo.budgetType === 1">房屋总面积：{{ detailInfo.houseArea || "-" }}/平方</div>
            <div>空间：{{ detailInfo.spaceItemNum || "-" }}项</div>
            <div>综合项：{{ detailInfo.comprehensiveNum || "-" }}项</div>
            <div>报价项：{{ detailInfo.budgetItemNum || "-" }}项</div>
          </div>
          <div class="left_content mb20" v-if="detailInfo.budgetType === 2">
            <div style="color: #3d3d3d; font-weight: 700">套餐价：¥{{ detailInfo.packageUnitPrice || "-" }}元/平</div>
            <div>可享受：{{ detailInfo.packageSquareNum || "-" }}/平方</div>
            <div>当前平方：{{ detailInfo.houseArea || "-" }}/平方</div>
            <div>每多出1/平方：费用按￥{{ detailInfo.packageUnitPrice || "-" }}</div>
          </div>
          <div class="left_discount mb20" v-if="detailInfo.regularViewStatus && detailInfo.specialViewStatus">
            <div>正价商品：{{ detailInfo.customerRegularDiscount || "-" }} %</div>
            <div>特价商品：{{ detailInfo.customerSpecialDiscount || "-" }} %</div>
          </div>
          <div class="left_price">
            <div>
              成交金额：<span class="price_num">¥{{ detailInfo.concludeMoney || "-" }}</span>
            </div>
            <div class="price_memo">备注：{{ detailInfo.remark || "--" }}</div>
          </div>
        </div>
        <div class="box_right">
          <div class="right_opreate">
            <div class="opreate_left">
              <el-button link @click="routeToExchange(1)">
                <img src="@/assets/images/back.png" />
                <span class="btn_text">退货单</span>
                <span class="corner_mark" v-if="detailInfo.returnProductNum > 0">
                  {{ detailInfo.returnProductNum < 99 ? detailInfo.returnProductNum : "99+" }}
                </span>
              </el-button>
              <span class="split_line"></span>
              <el-button link @click="routeToExchange(2)">
                <img src="@/assets/images/change.png" />
                <span class="btn_text">换补单</span>
                <span class="corner_mark" v-if="detailInfo.replacementProductNum > 0">
                  {{ detailInfo.replacementProductNum < 99 ? detailInfo.replacementProductNum : "99+" }}
                </span>
              </el-button>
            </div>
            <div class="opreate_right">
              <el-input class="right_input" v-model="searchKey" placeholder="请输入商品或定额名称">
                <template #suffix>
                  <el-button class="input_suffix" @click="filterSpaceList()">搜索</el-button>
                </template>
              </el-input>
            </div>
          </div>
          <div class="right_content">
            <div ref="tableList" class="table_list">
              <div class="list_box">
                <div class="space" v-for="(item, index) in detailInfo.spaceList" :key="item.spaceId">
                  <div>
                    <div class="title">
                      <div class="title_left">
                        <div class="name">{{ item.spaceName || "--" }}</div>
                        <div class="zone">
                          <span>（合计：</span>
                          <span class="high_light">¥{{ item.spaceTotalMoney || "--" }} / </span>
                          <span v-if="detailInfo.budgetType === 2">个性化增项：￥{{ item.customIncreaseMoney || "--" }} / </span>
                          <span>
                            {{
                              `面积：${item.area || "--"}㎡ 
                              长：${item.length || "--"}m 
                              宽：${item.width || "--"}m 
                              高：${item.height || "--"}m）`
                            }}
                          </span>
                        </div>
                      </div>
                      <div class="action">
                        <el-button type="primary" link @click="openSelectProd(item)">
                          材料<img src="@/assets/images/download-icon.png" class="ml8" />
                        </el-button>
                        <el-divider direction="vertical" />
                        <el-button type="primary" link @click="openQuota(item)">
                          定额<img src="@/assets/images/download-icon.png" class="ml8" />
                        </el-button>
                        <el-divider direction="vertical" />
                        <el-button type="primary" link @click="addCustomConfirm(item)"> 自定义定额 </el-button>
                      </div>
                    </div>
                    <div class="table">
                      <el-table
                        border
                        ref="spaceTable"
                        :data="tableData(item)"
                        style="width: 100%"
                        header-cell-class-name="table_head"
                        :span-method="temp => tableArraySpan(tableData(item), temp)"
                        @selection-change="select => handleSelectionChange(select, index)"
                      >
                        <el-table-column v-if="isAllDisabled(tableData(item)) === -1" fixed="left" width="55">
                          <template #header>
                            <el-checkbox disabled />
                          </template>
                          <template #default>
                            <el-checkbox disabled />
                          </template>
                        </el-table-column>
                        <el-table-column v-else type="selection" width="55" :selectable="row => row.canSelect" />
                        <el-table-column prop="mainPicUrl" label="图片" fixed="left" width="120">
                          <template #default="{ row }">
                            <span class="change_tag">
                              <img v-if="row.exchangeTag === 1" class="tag_image" src="@/assets/images/refund.png" />
                              <img v-if="row.exchangeTag === 2" class="tag_image" src="@/assets/images/exchange.png" />
                              <img v-if="row.exchangeTag === 3" class="tag_image" src="@/assets/images/supply.png" />
                            </span>
                            <img v-if="row.mainPicUrl" class="row_img" :src="row.mainPicUrl" />
                            <div v-else-if="row.type === 2" class="row_img" style="background: #f3f6f9">
                              <el-icon size="80" color="#E1E6ED"><UserFilled /></el-icon>
                            </div>
                            <span v-else>--</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="productName" label="商品名称" width="240" show-overflow-tooltip />
                        <el-table-column prop="brandName" label="品牌" width="90" />
                        <el-table-column prop="modeCode" label="型号" width="60" />
                        <el-table-column prop="unit" label="单位" width="60">
                          <template #default="{ row }">
                            {{ getName("shop_unit", row.unit) }}
                          </template>
                        </el-table-column>
                        <el-table-column prop="num" label="数量" width="80">
                          <template #default="{ row }">
                            <span v-if="row.exchangeNum" class="exchange_mark">退：{{ row.exchangeNum }}</span>
                            {{ row.num || "--" }}
                          </template>
                        </el-table-column>
                        <el-table-column prop="lostRate" label="耗损率" width="90" />
                        <el-table-column prop="productUnitPrice" label="材料单价" width="110" />
                        <el-table-column prop="workerUnitPrice" label="人工费单价" width="110" />
                        <el-table-column prop="unitTotalMoney" label="单项合计" width="110" />
                        <el-table-column prop="projectVal" label="预算工程量" width="110" />
                        <el-table-column prop="projectTotalMoney" label="汇总合计" width="110" />
                        <el-table-column prop="quotaName" label="工程项目名称" width="200" show-overflow-tooltip />
                        <el-table-column prop="standardDesc" label="材料及工艺说明" width="200" show-overflow-tooltip />
                        <el-table-column prop="remark" label="备注" min-width="320">
                          <template #default="{ row }">
                            <RemarkEditor v-model="row.remark" :isEdit="false" />
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="100">
                          <template #default="{ row }">
                            <el-popconfirm title="确定要取消退货吗?" v-if="row.canDelete" @confirm="delProductConfirm(row)">
                              <template #reference>
                                <el-button style="color: #ff3333" link>取消退货</el-button>
                              </template>
                            </el-popconfirm>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <div class="memo">
                      <div>备注说明</div>
                      <RemarkEditor v-model="item.remark" :isEdit="false" />
                    </div>
                  </div>
                </div>
                <div class="space">
                  <div id="comprehensive">
                    <div class="title">
                      <div class="title_left">
                        <div class="name">综合项</div>
                        <div class="zone">
                          （合计：
                          <!--  TODO 缺少字段 -->
                          <span class="high_light">¥{{ detailInfo.comprehensiveTotal }}</span>
                          ）
                        </div>
                      </div>
                    </div>
                    <div class="table">
                      <el-table
                        :data="detailInfo.comprehensiveList"
                        stripe
                        style="width: 100%"
                        header-cell-class-name="table_head"
                      >
                        <el-table-column type="index" label="序号" fixed="left" width="80" />
                        <el-table-column prop="itemName" label="项目名称" fixed="left" />
                        <el-table-column prop="moneyType" label="属性">
                          <template #default="{ row }">{{ getName("shop_budget_money_type", row.moneyType) }}</template>
                        </el-table-column>
                        <el-table-column prop="unit" label="单位" width="100">
                          <template #default="{ row }">{{ row.unit || "元" }}</template>
                        </el-table-column>
                        <el-table-column prop="linkTypesDesc" label="关联报价" />
                        <el-table-column prop="feeRate" label="单价/比例" />
                        <el-table-column prop="itemMoney" label="总价" />
                        <el-table-column prop="remark" label="说明备注" />
                      </el-table>
                    </div>
                    <div class="tax">
                      <div class="tax_box">
                        <div class="tax_title">
                          <el-tooltip effect="dark" content="管理费=预算汇总表中的不含税造价X管理费率" placement="top">
                            <el-icon style="color: #909399"><QuestionFilled /></el-icon>
                          </el-tooltip>
                          <div>管理费</div>
                        </div>
                        <div class="tax_input">
                          <span>比例</span>
                          <el-input disabled style="width: 140px" v-model="detailInfo.managerFeeRate">
                            <template #suffix>%</template>
                          </el-input>
                        </div>
                      </div>
                      <div class="tax_box">
                        <div class="tax_title">
                          <el-tooltip effect="dark" content="管理费=预算汇总表中的不含税造价X管理费率" placement="top">
                            <el-icon style="color: #909399"><QuestionFilled /></el-icon>
                          </el-tooltip>
                          <div>税金费用</div>
                        </div>
                        <div class="tax_input">
                          <span>比例</span>
                          <el-input disabled style="width: 140px" v-model="detailInfo.taxesRate">
                            <template #suffix>%</template>
                          </el-input>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div id="summary">
                    <div class="title">
                      <div class="title_left">
                        <div class="name">预算汇总表</div>
                      </div>
                    </div>
                    <div class="table">
                      <el-table
                        :data="detailInfo.budgetSummaryVO?.itemList"
                        stripe
                        style="width: 100%"
                        header-cell-class-name="table_head"
                      >
                        <el-table-column type="index" label="序号" fixed="left" width="60" />
                        <el-table-column prop="itemName" label="类别名称" fixed="left" />
                        <el-table-column prop="itemDesc" label="计算明细" />
                        <el-table-column prop="amount" label="价格" />
                      </el-table>
                    </div>
                    <div class="memo">
                      <div>备注说明</div>
                      <div class="table_remark" v-html="detailInfo.budgetSummaryVO?.remark" />
                    </div>
                  </div>
                </div>
              </div>
              <div class="affix">
                <el-affix position="bottom" :offset="21" style="width: 100%" target=".right_content">
                  <div class="affix_content">
                    <div class="content_select">
                      <span>
                        已选择：
                        <span class="select_num">{{ selectedNum }}</span>
                        项
                      </span>
                      <el-button link @click="cancelSelect()">取消选择</el-button>
                    </div>
                    <div class="content_btn">
                      <el-button :disabled="!selectedNum" class="btn_back" @click="addExchangeProduct(1)">仅退货</el-button>
                      <el-button :disabled="!selectedNum" class="btn_exchange" @click="addExchangeProduct(2)">退换货</el-button>
                    </div>
                  </div>
                </el-affix>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <selectProduct
      :doSubmit="false"
      :optionInfo="prodOptionInfo"
      @close="closeSelectProDialog()"
      @customSubmit="addMaterialConfirm"
    />

    <quota v-model:isOpen="quotaDialogFlag" :doSubmit="false" :optionInfo="optionInfoQuota" @customSubmit="addQuotaConfirm" />
  </div>
</template>
<script setup>
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import searchBox from "@/views/home/components/search";
import RemarkEditor from "@/components/RemarkEditor";
import useCodeArrStore from "@/store/modules/select";
import quota from "./components/quota.vue";
import selectProduct from "./components/selectProduct.vue";
import {
  getBudgetExchangeDetail,
  addBudgetExchangeProduct,
  addExchangeQuota,
  addExchangeMaterial,
  addExchangeCustom,
  delExchangeProduct
} from "@/apis/quote-price/following";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const budgetId = route.query.budgetId;
const customerId = route.query.customerId;
const contractId = route.query.contractId;
const afterSalesType = route.query.afterSalesType;
const reformId = route.query.reformId;
const spaceTable = ref();
const detailInfo = ref({});
const detailInfoCache = ref({});
const loading = ref(false);
const selectedList = ref([]);
const searchKey = ref("");
const currSpace = ref({});

const prodOptionInfo = ref({});
const optionInfoQuota = ref({});
const quotaDialogFlag = ref(false);

const selectedNum = computed(() => selectedList.value.flat().length);

const tableData = item => [...(item.quotaItemList || []), ...(item.specialQuotaItemList || [])];
const getName = (dictType, code) => useCodeArrStore().getDictName(dictType, code);

const isAllDisabled = list => list.findIndex(({ canSelect }) => canSelect);

const getExchangeDetail = async () => {
  loading.value = true;
  const { data } = await getBudgetExchangeDetail(budgetId);
  detailInfo.value = data;
  detailInfoCache.value = JSON.parse(JSON.stringify(data));
  filterSpaceList();
  loading.value = false;
};

const filterSpaceList = () => {
  detailInfo.value.spaceList = detailInfoCache.value.spaceList.map(space => ({
    ...space,
    quotaItemList: space.quotaItemList?.filter(item => {
      if (!searchKey.value) return true;
      else return item.productName?.indexOf(searchKey.value) > 0;
    })
  }));
};

const handleSelectionChange = (item, index) => {
  selectedList.value[index] = item;
};

const cancelSelect = () => {
  spaceTable.value.forEach(space => {
    space.clearSelection();
  });
  selectedList.value = [];
};

const addExchangeProduct = async type => {
  await addBudgetExchangeProduct({
    budgetId: detailInfo.value.budgetId,
    type,
    productIds: selectedList.value.flat().map(({ id, type }) => ({ id, type }))
  });
  selectedList.value = [];
  routeToExchange(1);
};

const openSelectProd = item => {
  currSpace.value = item;
  prodOptionInfo.value.type = detailInfo.value.budgetType;
  prodOptionInfo.value.isShow = true;
};

const closeSelectProDialog = () => (prodOptionInfo.value.isShow = false);

const addMaterialConfirm = async skuIds => {
  await addExchangeMaterial({ budgetId, skuIds, spaceId: currSpace.value.spaceId });
  routeToExchange(2);
};

const openQuota = item => {
  currSpace.value = item;
  optionInfoQuota.value.budgetId = detailInfo.value.budgetId;
  optionInfoQuota.value.type = detailInfo.value.budgetType;
  quotaDialogFlag.value = true;
};

const addQuotaConfirm = async quotaIds => {
  await addExchangeQuota({ quotaIds, budgetId, spaceId: currSpace.value.spaceId });
  routeToExchange(2);
};

const addCustomConfirm = async item => {
  currSpace.value = item;
  await addExchangeCustom({ budgetId, spaceId: currSpace.value.spaceId });
  routeToExchange(2);
};

const delProductConfirm = async ({ id, type }) => {
  await delExchangeProduct({ id, type, budgetId });
  handleSuccess("取消退货成功");
};

const routeToExchange = orderType => {
  router.push({
    path: "/quote-price/following/exchange",
    query: {
      budgetId: detailInfo.value.budgetId,
      orderType,
      contractId,
      customerId,
      reformId,
      afterSalesType,
      returnNum: detailInfo.value.returnProductNum,
      replacementNum: detailInfo.value.replacementProductNum
    }
  });
};

const handleSuccess = message => {
  ElMessage({ message, type: "success" });
  getExchangeDetail();
};

let contentIdList = [];
const tableArraySpan = (table, { row, rowIndex, columnIndex }) => {
  let span;
  if (!table) return;

  if ([11, 12, 13, 14, 15].indexOf(columnIndex) > -1) {
    if (!row.contentId) return;
    if (contentIdList[columnIndex] === row.contentId) span = [0, 1];
    else {
      contentIdList[columnIndex] = row.contentId;
      const rows = table.filter(item => {
        return item.contentId === contentIdList[columnIndex];
      });
      const count = rows.length;
      if (count > 1) {
        span = [count, 1];
      }
    }

    if (rowIndex === table.length - 1) contentIdList[columnIndex] = null;

    return span;
  }
};

(() => {
  getExchangeDetail();
})();
</script>

<style lang="scss">
.following_change {
  height: calc(100% - 114px);
  margin-top: 114px;
  overflow: hidden;
  .change_content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 20px 15px 15px 20px;
    .content_box {
      height: 100%;
      display: grid;
      grid-template-columns: 240px calc(100% - 240px);
      grid-template-rows: 100%;
      border-radius: 10px;
      background: white;
    }
    .box_left {
      border-right: 1px solid #e1e6ed;
      padding: 20px;
      .left_title {
        font-size: 16px;
        line-height: 24px;
        color: #4e5969;
      }
      .left_content {
        display: grid;
        gap: 10px;
        color: #86909c;
        line-height: 24px;
        .content_title {
          font-size: 16px;
          font-weight: 700;
          color: #3d3d3d;
          .title_num {
            color: #ff3333;
          }
        }
      }
      .left_discount {
        display: grid;
        color: #3d3d3d;
        gap: 10px;
        line-height: 24px;
        font-weight: 700;
      }
      .left_price {
        display: grid;
        gap: 10px;
        font-weight: 700;
        color: #606266;
        .price_num {
          color: #3d3d3d;
        }
        .price_memo {
          font-size: 12px;
          font-weight: 400;
          color: #86909c;
          line-height: 24px;
        }
      }
    }
    .box_right {
      height: 100%;
      background: white;
      overflow: hidden;
      .right_opreate {
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 4px 24px 0;
        height: 50px;
        border-bottom: 1px solid #e1e6ed;
        .opreate_left {
          display: flex;
          align-items: center;
          gap: 18px;
          .corner_mark {
            position: relative;
            bottom: 14px;
            right: 0;
            box-sizing: border-box;
            padding: 0 6px 0 5px;
            font-size: 12px;
            line-height: 18px;
            background: red;
            color: white;
            border-radius: 999px 999px 999px 0px;
          }
          .btn_text {
            color: #213270;
            margin-left: 8px;
          }
          .split_line {
            display: inline-block;
            width: 4px;
            height: 20px;
            border-radius: 2px;
            background: #dcdfe6;
          }
        }
        .opreate_right {
          display: flex;
          align-items: center;
          gap: 20px;
          .right_input {
            width: 360px;
            border-radius: 16px;
            overflow: hidden;
            .input_suffix {
              background: #4e5969;
              color: white;
              border-radius: 15px;
              height: 24px;
              font-size: 12px;
            }
            .el-input__wrapper {
              box-shadow: none !important;
              padding: 0 5px 0 15px;
            }
          }
          .right_btn {
            background: #f2f3f5;
            color: #1d2129;
            border: 0;
            width: 120px;
          }
        }
      }
      .right_content {
        box-sizing: border-box;
        height: calc(100% - 50px);
        overflow: hidden;
        .table_list {
          height: 100%;
          overflow: auto;
          box-sizing: border-box;
          background: #f5f7fa;
          .list_box {
            min-height: calc(100% - 66px);
          }
          .row_img {
            display: block;
            width: 80px;
            height: 80px;
            margin: 0 auto;
            border-radius: 4px;
          }
          .space {
            padding: 20px;
            margin-bottom: 20px;
            background: white;
            .title {
              display: flex;
              justify-content: space-between;
              .title_left {
                display: flex;
                font-size: 18px;
                color: #3d3d3d;
                align-items: end;
                .name {
                  font-weight: 700;
                }
                .zone {
                  font-size: 14px;
                  color: #4e5969;
                  line-height: 18px;
                  .high_light {
                    color: #ff3333;
                  }
                }
              }
              .action {
                display: flex;
                color: #007dff;
                gap: 12px;
                align-items: center;
                .split_line {
                  border-left: 1px solid #e1e6ed;
                  margin: 3px 0;
                }
                .material,
                .quota {
                  display: flex;
                  align-items: center;
                  gap: 10px;
                }
              }
            }
            .table {
              margin: 20px 0;
              border: 1px solid #e1e6ed;
              .is-checked .el-checkbox__inner {
                background: #213270;
                border-color: #213270;
              }
              .is-indeterminate .el-checkbox__inner {
                background: #213270;
                border-color: #213270;
              }
              .table_head {
                background: #ebeef1;
              }
            }
            .memo {
              display: grid;
              grid-template-columns: 60px 1fr;
              align-items: center;
              gap: 10px;
              color: #4e5969;
              .table_remark {
                border: 1px solid #e1e6ed;
                padding: 10px 18px;
              }
            }
            .tax {
              display: flex;
              gap: 20px;
              margin-bottom: 30px;
              .tax_box {
                width: 270px;
                .tax_title {
                  display: flex;
                  align-items: center;
                  margin-bottom: 20px;
                  font-size: 18px;
                  font-weight: 700;
                  color: #3d3d3d;
                  .tip {
                    margin-right: 10px;
                  }
                }
                .tax_input {
                  display: flex;
                  gap: 10px;
                  align-items: center;
                }
              }
            }
          }
          .affix {
            .affix_content {
              display: flex;
              justify-content: space-between;
              align-items: center;
              box-sizing: border-box;
              background: white;
              box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.15);
              padding: 17px;
              .content_select {
                display: flex;
                align-items: center;
                gap: 20px;
                color: #86909c;
                .select_num {
                  color: #ff3333;
                }
              }
              .content_btn {
                .btn_back,
                .btn_exchange {
                  width: 120px;
                  color: white;
                  border: 0;
                  border-radius: 2px;
                }
                .btn_back {
                  background: #d54941;
                }
                .btn_back.is-disabled {
                  background: #eaa4a0;
                }
                .btn_exchange {
                  background: #424e66;
                }
                .btn_exchange.is-disabled {
                  background: #a0a6b2;
                }
              }
            }
          }
        }
      }
    }
  }
  .change_tag {
    float: left;
    position: absolute;
    top: 0;
    left: 0;
    .tag_image {
      position: absolute;
    }
  }
  .exchange_mark {
    position: absolute;
    left: 0;
    top: 0;
    height: 20px;
    border-radius: 0px 0px 5px 0px;
    background: #d54941;
    color: white;
    line-height: 20px;
    padding: 0 6px;
    font-size: 12px;
  }
  .is-disabled .el-input__wrapper {
    background: white !important;
  }
}
</style>
